<?php

require_once(CLASS_PATH . 'medoo.min.php');

//实现wechat数据库操作方法
class database {

    protected $medoo, $table;

    public function __construct($table = '') {
        $this->logger = new logger();
        $this->medoo = new medoo(
                array(
            'database_type' => 'mysql',
            'database_name' => MYSQL_DATABASE,
            'server' => MYSQL_SERVER,
            'username' => MYSQL_USER,
            'password' => MYSQL_PASSWORD,
                )
        );
        $this->table = $table;
    }

    /**
     * 新增
     * @param type $fields
     * @return type
     */
    public function insert($fields) {
        $id = $this->medoo->insert($this->table, $fields);
        $error = $this->medoo->error();
        if ($error[0] != '00000') {
           print_r('Mysql error: ' . $error[2]);
        }
        return $id;
    }
    
    public function query_all($sql){
        return $this->medoo->query($sql)->fetchAll();
    } 







//================================PRODUCT=================================================
    /**
     * 查询所有产品
     * @return array 
     */
    public function find_all_product() {
        $result = $this->medoo->select($this->table, "*");
        $error = $this->medoo->error();
        if ($error[0] != '00000') {
             print_r('Mysql error: ' . $error[2]);
        }
        return $result ? $result : array();
    }

    /**
     * 按条件查询产品
     * @param array $arr
     * @return array
     */
    public function find_product($arr) {
        if (!is_array($arr)) {
            return array();
        }
        $result = $this->medoo->select($this->table, "*", array('AND' => $arr));
        $error = $this->medoo->error();
        if ($error[0] != '00000') {
             print_r('Mysql error: ' . $error[2]);
        }
        return $result ? $result : array();
    }

    /**
     * 更新产品
     * @param type $arr_data
     * @param type $arr_where
     * @return type
     */
    public function update_product($arr_data, $arr_where = null) {
        $result = $this->medoo->update($this->table, $arr_data, $arr_where);
        $error = $this->medoo->error();
        if ($error[0] != '00000') {
             print_r('Mysql error: ' . $error[2]);
            print_r($error);
        }
        return $result ? $result : array();
    }

    public function find_brand() {
        $sql = 'SELECT DISTINCT brand FROM ' . $this->table;
        $result = $this->medoo->query($sql)->fetchAll();
        $error = $this->medoo->error();
        if ($error[0] != '00000') {
             print_r('Mysql error: ' . $error[2]);
        }
        return $result ? $result : array();
    }

}

?>